package com.whfc.iot.mach.codec;

import com.whfc.iot.mach.constant.MsgConst;
import com.whfc.iot.mach.entity.MachMsg0x08;
import com.whfc.iot.mach.entity.MachWarnrotation;
import com.whfc.iot.util.MsgDataCodecUtil;
import io.netty.buffer.ByteBuf;

import java.util.Date;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/7/17 9:32
 */
public class MachMsgDataCodec0x08 implements MachMsgDataCodec<MachMsg0x08> {

    @Override
    public void decode(ByteBuf buf, MachMsg0x08 msg) {

        //报警
        while (buf.readableBytes() > 1) {
            int warnType = buf.readUnsignedByte();
            if (MsgConst.WARN_TYPE_ROTARY == warnType) {
                //时间
                Date warnTime = MsgDataCodecUtil.readDateTime(buf);
                //角度
                int rotationX = buf.readUnsignedShort();
                int rotationZ = buf.readUnsignedShort();
                MachWarnrotation warn = new MachWarnrotation();
                warn.setWarnTime(warnTime);
                warn.setRotationX(rotationX / 10);
                warn.setRotationZ(rotationZ / 10);
                msg.setRotation(warn);
            }
        }
    }

    @Override
    public void encode(ByteBuf buf, MachMsg0x08 msg) {

        //报警
        MachWarnrotation rotation = msg.getRotation();
        if (rotation != null) {
            buf.writeByte(rotation.warnType());
            //时间
            MsgDataCodecUtil.writeDateTime(buf, rotation.getWarnTime());
            //角度
            buf.writeShort((int) (rotation.getRotationX() * 10));
            buf.writeShort((int) (rotation.getRotationZ() * 10));
        }
    }
}
